#!/bin/bash

# # 清理所有192.168.144.*的旧路由规则
# echo "=== 旧路由规则 ==="
# ip route show | grep '192.168.45.' | while read -r line; do
#     echo "发现旧规则：$line"
# done
# echo "------------------------"



#获取所有拓展坞设备信息
echo "=== 扫描网络设备 ==="
devices=()
ips=()
while read -r entry; do
    # 提取IP
    ip_full=$(echo "$entry" | grep -oP '192.168.45.\d+')
    
    # 去掉 192.168.45.255
    for ip in $ip_full; do
        if [[ "$ip" != "192.168.45.255" ]]; then
            dev=$(echo "$entry" | awk '{print $2}')
            ips+=("$ip")
            devices+=("$dev")
            echo "识别并重启设备：$dev (IP: $ip)"
            nmcli device reapply $dev #不能直接删除，需要重启来清空规则
        fi
    done
done < <(ip -o addr show | grep 'inet 192.168.45.')
echo "------------------------"

# 动态生成并添加路由规则
echo "=== 添加新路由规则 ==="
for i in "${!ips[@]}"; do
    ip="${ips[$i]}"
    dev="${devices[$i]}"
    
    # 计算目标 IP 地址
    target_octet=$(echo "$ip" | awk -F. '{print $4 - 80}')
    target_ip="192.168.144.$target_octet"
    # 只有当ip合法时才添加路由
    if [[ "$target_ip" =~ ^192\.168\.144\.[0-9]+$ ]]; then
        sudo ip route add "$target_ip" via 192.168.45.1 dev "$dev"
        echo "已添加：$target_ip → 设备 $dev (源IP: $ip)"
    else
        echo "错误: 无效的目标IP地址：$target_ip"
    fi
done
echo "------------------------"

echo "=== 测试连通性 ==="
success=0
total=0
for ip in "${ips[@]}"; do
    target_octet=$(echo "$ip" | awk -F. '{print $4 - 80}')
    target_ip="192.168.144.$target_octet"
    ((total++))
    
    if ping -c 1 -W 1 "$target_ip" &> /dev/null; then
        echo "[成功] $target_ip 可达"
        ((success++))
    else
        echo "[失败] $target_ip 不可达"
    fi
done
echo "成功率：$success/$total"
echo "------------------------"

echo "=== 当前路由表 ==="
ip route show
